<?php
define('UPLOAD_PATH','./img/');
function img_localhost($url,$max_w=0,$max_h=0,$sy=false,$flag=true){
	$cache_path=str_replace(UPLOAD_PATH, "./img/cache/img_w{$max_w}_h{$max_h}/", $url).'.png';
	if(file_exists($cache_path)){
		return rooturl.$cache_path;
	}
	if(!file_exists(dirname($cache_path))){
		mkpath(dirname($cache_path));
	}

	$finfo = finfo_open(FILEINFO_MIME);
	$type = explode('/', array_shift(explode(';', finfo_file($finfo, rootpath.$url))));
	$type=$type[1];
	if($type=='jpg') $type='jpeg';
	if(!in_array($type, array('jpeg','gif','png'))){
		return false;
	}
	$open_fn = 'imagecreatefrom'.$type;
	$src = $open_fn($url);
	$dst = imagecreatetruecolor($max_w,$max_h);
	$src_w = imagesx($src); 
	$src_h = imagesy($src);
	if ($flag) { //等比
		if ($max_w/$max_h < $src_w/$src_h) {
			$dst_w = $max_w;					//横屏图片以宽为标准
			$dst_h = $max_w * $src_h/$src_w;
		}else{
			$dst_h = $max_h;					//竖屏图片以高为标准
			$dst_w = $max_h * $src_w/$src_h;
		}
		$dst_x=(int)(($max_w-$dst_w)/2);		//在目标图上显示的位置
		$dst_y=(int)(($max_h-$dst_h)/2);
	}else{    //不等比
		$dst_x=$dst_y=0;
		$dst_w=$max_w;
		$dst_h=$max_h;
	}
	imagecopyresampled($dst,$src,$dst_x,$dst_y,0,0,$dst_w,$dst_h,$src_w,$src_h);
	$res = imagepng($dst,$cache_path);
	imagedestroy($dst);
	imagedestroy($src);
	return rooturl.$cache_path;
}


?>